import React, { useEffect, useState } from 'react'
import './Task.less'
import { Button, Tag, Table, Modal, Form, Input, DatePicker, Popconfirm, message } from 'antd'
import { getTaskList, addTask, removeTask, completeTask } from '../../api';



export default function Task2() {
  let [selectedIndex, setSelectedIndex] = useState(0),
    [tableData, setTableData] = useState([]),
    [tableLoading, setTableLoading] = useState(false),
    [modalVisible, setModalVisible] = useState(false),
    [confirmLoading, setConfirmLoading] = useState(false)

  /* 对日期处理的方法 */
  function zero(text) {
    text = String(text);
    return text.length < 2 ? '0' + text : text;
  };

  function formatTime(time) {
    let arr = time.match(/\d+/g),
      [year, month, day, hours = '00', minutes = '00'] = arr;
    return `${year}-${zero(month)}-${zero(day)} ${zero(hours)}:${zero(minutes)}`;
  };

  async function handeleRemove(id) {
    try {
      let { code } = await removeTask(id)
      if (+code === 0) {
        queryData()
        message.success('恭喜您，操作成功了！')
      } else {
        message.error('很遗憾，操作失败了，请稍后再试！');
      }
    } catch (err) { }
  }

  async function handleUpdate(id) {
    try {
      let { code } = await completeTask(id);
      if (+code === 0) {
        queryData();
        message.success('恭喜您，操作成功了！');
      } else {
        message.error('很遗憾，操作失败了，请稍后再试！');
      }
    } catch (_) { }
  }

  let columns = [
    {
      title: '编号',
      dataIndex: 'id',
      align: 'center',
      width: '8%'
    },
    {
      title: '任务描述',
      dataIndex: 'task',
      // id: 'age',
    },
    {
      title: '状态',
      dataIndex: 'state',
      width: '10%',
      align: 'center',
      render: text => +text === 1 ? '未完成' : '已完成'
    },
    {
      title: '完成时间',
      dataIndex: 'complete',
      align: 'center',
      width: '20%',
      render: (res, record) => {

        let { state, time, complete } = record
        if (+state === 2) time = complete
        return formatTime(time);
      }
    },
    {
      title: '操作',
      render: (_, record) => {
        let { id, state } = record
        return <>
          <Popconfirm title="您确定要删除此任务吗？"
            onConfirm={() => handeleRemove(id)}>
            <Button type="link">删除</Button>
          </Popconfirm>
          {+state !== 2 ? <Popconfirm title="您确把此任务设置为完成吗？"
            onConfirm={() => handleUpdate(id)}>
            <Button type="link">完成</Button>
          </Popconfirm> : null}
        </>
      }
      // dataIndex: 'address',
      // id: 'address',
    },
  ]

  const closeModal = () => {
    setModalVisible(false)
    setConfirmLoading(false)
  }

  const submit = async () => {
    try {

    } catch (err) {
      setConfirmLoading(false)
    }
  }

  const queryData = async () => {
    setTableLoading(true)
    try {
      let { code, list } = await getTaskList(selectedIndex);
      if (+code !== 0) list = [];
      setTableData(list)

    } catch (err) { }
    setTableLoading(false)
  }

  useEffect(() => {
    queryData()
  }, [selectedIndex])

  return (
    <div className='task_box'>
      <div className="header">
        <h1>TASK OA 任务管理器系统</h1>
        <Button type='primary' onClick={() => {
          setModalVisible(true)
        }}>
          新增任务
        </Button>
      </div>

      <div className="tag_box">
        {['全部', '未完成', '已完成'].map((item, index) => {
          return <Tag
            key={index}
            onClick={() => {
              setSelectedIndex(index)
            }}
            color={selectedIndex === index ? '#1677ff' : ''}
          >{item}</Tag>
        })}
      </div>

      <Table
        dataSource={tableData}
        columns={columns}
        rowKey='id'
        pagination={false}
        loading={tableLoading}
      />

      <Modal
        title="新增任务窗口"
        okText="确认提交"
        open={modalVisible}
        confirmLoading={confirmLoading}
        onCancel={closeModal}
        submit={submit}
      >
        <Form
          layout="vertical"
          initialValues={{ task: '', time: '' }}
        >
          <Form.Item label="任务描述" name="task" validateTrigger="onBlur"
            rules={[
              { required: true, message: '任务描述是必填项' },
              { min: 6, message: '输入的内容至少6位及以上' }
            ]}>
            <Input.TextArea rows={4}></Input.TextArea>
          </Form.Item>
          <Form.Item label="预期完成时间" name="time" validateTrigger="onBlur"
            rules={[
              { required: true, message: '预期完成时间是必填项' }
            ]}>
            <DatePicker showTime />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
